<template>
<div class="container">
  <el-row :gutter="24">
    <el-col :span="12" class="left">
      <div class="title">新增商户券:</div>
      <el-form size="medium" :model="ruleForm" :rules="rules" :disabled="isTrue" ref="ruleForm" label-width="110px" class="demo-ruleForm">
        <el-form-item label="可用油站：" prop="gasId">
          <el-row :gutter="24">
            <el-col :span="12">
              <el-select @change="changeOil" style="width: 317px;" v-model="ruleForm.gasId" placeholder="请选择可用油站">
                <el-option v-for="item in gasOptions" :key="item.gasId"  :label="item.gasName" :value="`${item.gasId}_${item.gasName}`"></el-option>
              </el-select>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="优惠券名称：" prop="couponTitle">
          <el-row :gutter="24">
            <el-col :span="12">
              <el-input maxlength="10" v-model="ruleForm.couponTitle" placeholder="请输入优惠券名称"></el-input>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="优惠券类型：" prop="couponType" class="star">
          <el-row :gutter="24">
            <el-col :span="12">
              <el-radio-group v-model="ruleForm.couponType">
                <el-radio label="1001">固定面额券</el-radio>
              </el-radio-group>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="优惠券面额：" prop="couponMoney">
          <el-row :gutter="24">
            <el-col :span="12">
              <el-input v-model="ruleForm.couponMoney" :placeholder="placeholder('1')"></el-input>
            </el-col>
            <el-col :span="1">元</el-col>
            <el-col :span="8">
              <!-- <div class="quan">
                <span v-if="Object.keys(valid).length > 0">金额限制在{{valid.coupon_amount_limit.min}}-{{valid.coupon_amount_limit.max}}之间</span>
              </div> -->
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="使用门槛：" prop="couponConditionMoney">
          <el-row :gutter="24">
            <el-col :span="12">
              <el-input v-model="ruleForm.couponConditionMoney" :placeholder="placeholder('2')"></el-input>
            </el-col>
            <el-col :span="1">元</el-col>
            <el-col :span="8">
              <!-- <div class="quan">
                <span v-if="Object.keys(valid).length > 0">金额限制在{{valid.coupon_amount_use_limit.min}}-{{valid.coupon_amount_use_limit.max}}之间</span>
              </div> -->
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="券有效期：" prop="expireDateInterval">
          <el-row :gutter="24">
            <el-col :span="12">
              <el-input v-model="ruleForm.expireDateInterval" :placeholder="placeholder('3')"></el-input>
            </el-col>
            <el-col :span="1">天</el-col>
            <el-col :span="8">
              <!-- <div class="quan">
                <span  v-if="Object.keys(valid).length > 0">时间限制在{{valid.coupon_day_use_limit.min}}-{{valid.coupon_day_use_limit.max}}之间</span>
              </div> -->
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="可用油品：" prop="oils">
          <div v-if="!oilsOptions.length" style="color: #C0C4CC;">请先选择有油号的油站</div>
          <el-checkbox-group v-else v-model="ruleForm.oils" @change="handelCheck">
            <el-checkbox label="全部油品"></el-checkbox>
            <el-checkbox v-for="item in oilsOptions" :label="String(item.id)" :key="item.id" :disabled="checkDisabled">{{item.oilNum}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item v-if="!id">
          <el-button @click="back">返回</el-button>
          <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
        </el-form-item>
      </el-form>
      <el-button style="margin-left: 20px;" v-if="id" type="primary" @click="back">返回</el-button>
    </el-col>
    <el-col :span="12" class="left">
      <div class="title">样式预览图如下:</div>
      <div class="wrap">
        <div class="top">
          <div class="top_left">
            <div>￥{{ruleForm.couponMoney}}</div>
            <div>加油满 {{ruleForm.couponConditionMoney}} 元可用</div>
          </div>
          <div class="top_right">
            <div class="name" v-if="ruleForm.couponTitle !== ''">{{ruleForm.couponTitle}}</div>
            <div class="name" v-else>优惠券名称</div>
            <div>仅适用于{{oilCouponName}}使用</div>
          </div>
        </div>
        <div class="bo"></div>
        <div class="middle">
          <span v-if="ruleForm.oils.length">仅限 {{String(oilName)}} 可用</span>
          <span v-else>选择可用油品</span>
        </div>
      </div>
      <div class="bottom">
        <div>
          <ul>
            <li>优惠券使用规则</li>
            <li>1、每次使用一张；</li>
            <li>2、不兑换、不找零；</li>
            <li>3、下单后，默认使用金额最高的一张；</li>
            <li>4、无需预约、消费高峰时可能需要等位；</li>
          </ul>
        </div>
      </div>
    </el-col>
  </el-row>
</div>
</template>

<script>
import { addCoupon, searchGas, checkDoor, getAllGasInfoList, checkCoupon, conponCheckNum } from '@api/market'
export default {
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入优惠券面额'))
      } else if (value < this.valid.coupon_amount_limit.min || value > this.valid.coupon_amount_limit.max || !/(^[1-9]\d*$)/.test(value)) {
        callback(new Error(`请输入${this.valid.coupon_amount_limit.min }-${this.valid.coupon_amount_limit.max}范围正整数`))
      } else {
        callback()
      }
    }
    const validatePassUse = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入使用门槛'))
      } else if (value && this.ruleForm.couponMoney === '') {
         callback(new Error('请先输入优惠券面额'))
      } else if (value &&  value < this.ruleForm.couponMoney * 5) {
         callback(new Error('使用门槛金额需是优惠券面额5倍以上'))
      } else if (value < this.valid.coupon_amount_use_limit.min || value > this.valid.coupon_amount_use_limit.max || !/(^[1-9]\d*$)/.test(value)) {
        callback(new Error(`请输入${this.valid.coupon_amount_use_limit.min }-${this.valid.coupon_amount_use_limit.max}范围正整数`))
      } else {
        callback()
      }
    }
    const validatePassTime = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入券有效期'));
      } else if (value < this.valid.coupon_day_use_limit.min || value > this.valid.coupon_day_use_limit.max || !/(^[1-9]\d*$)/.test(value)) {
        callback(new Error(`请输入${this.valid.coupon_day_use_limit.min }-${this.valid.coupon_day_use_limit.max}范围正整数`))
      } else {
        callback()
      }
    }
    return {
      checkDisabled: false,
      isTrue: false,
      id: '',
      ruleForm: {
        gasId: '', // 油站id
        couponTitle: '', // 优惠券名称
        couponType: '1001', // 优惠券类型
        couponMoney: '', // 优惠券面额
        couponConditionMoney: '', // 使用门槛
        expireDateInterval: '', // 券有效期
        oils: [] // 可用油号
      },
      oilCouponName: '', // 仅适用xx油站
      valid: {
        coupon_amount_limit: {},
        coupon_amount_use_limit: {},
        coupon_day_use_limit: {},
        max_user_size: {}
      }, // 校验数据
      oilsOptions: [], // 油号仓库
      gasOptions: [], // 油站仓库
      rules: {
        gasId: [{ required: true, message: '请选择可用油站', trigger: 'change' }],
        couponTitle: [{ required: true, message: '请输入优惠券名称', trigger: 'change' }],
        couponType: [{ required: true, message: '请选择优惠券类型', trigger: 'change' }],
        couponMoney: [{ required: true, message: '请输入优惠券面额'}, { validator: validatePass, trigger: 'change' }],
        couponConditionMoney: [{ required: true, message: '请输入使用门槛'}, { validator: validatePassUse, trigger: 'change' }],
        expireDateInterval: [{ required: true, message: '请输入券有效期'}, { validator: validatePassTime, trigger: 'change' }],
        oils: [{ required: true, message: '请选择油号', trigger: 'change' }]
      }
    }
  },
  computed: {
    oilName () {
      return this.getArrDifference(this.oilsOptions, this.ruleForm.oils)
    }
  },
  mounted () {
    const id = this.$route.query.mark
    this.id = id
    this.getAllGasStationsApi()
    this.checkDoorApi()
    if (this.id) {
      this.detailApi(id)
      this.isTrue = true
    }
  },
  methods: {
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.addCouponApi(this.ruleForm)
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    placeholder(type) {
      switch (type) {
        case '1':
          return `请输入${this.valid.coupon_amount_limit.min}-${this.valid.coupon_amount_limit.max}元优惠券面额`
        case '2':
          return `请输入${this.valid.coupon_amount_use_limit.min}-${this.valid.coupon_amount_use_limit.max}元使用门槛`
        case '3':
          return `请输入${this.valid.coupon_day_use_limit.min}-${this.valid.coupon_day_use_limit.max}天有效期`
      }
    },
    // 返回
    back () {
      this.$router.push({ path: '/marketCenter/coupon' })
    },
    // 循环匹配展示方法
    getArrDifference (arrHouse, arrData) {
      if (arrData[arrData.length - 1] === '全部油品') { return ['全部油品'] }
      const data = []
      arrHouse.forEach(item => {
        if (arrData.some(i => Number(i) === item.id)) {
          data.push(item.oilNum)
        }
      })
      return data
    },
    // 切换油站调取油号的接口
    async changeOil (val) {
      const m = val.split('_')[0]
      this.oilCouponName = val.split('_')[1]
      const res = await conponCheckNum({ gasId: m })
      if (!res.result) {
        this.$message.warning(res.message)
        this.ruleForm.gasId = ''
       }
      this.searchGasApi(m)
    },
    // 油号全部油品选择逻辑
    handelCheck (val) {
      if (val[val.length - 1] === '全部油品') {
        this.ruleForm.oils = ['全部油品']
        this.checkDisabled = true
      } else {
        this.checkDisabled = false
      }
    },
    // 新增优惠券接口
    async addCouponApi (data) {
      const dataCopy = Object.assign({}, data)
      dataCopy.gasId = data.gasId.split('_')[0]
      dataCopy.gasName = data.gasId.split('_')[1]
      if (data.oils[data.oils.length - 1] === '全部油品') {
        dataCopy.oils = ''
      } else {
        dataCopy.oils = data.oils.join(',')
      }
      try {
        const { code } = await addCoupon(dataCopy)
        if (code !== 200) return
        this.$router.push({ path: '/marketCenter/coupon' })
      } catch (err) {
        console.log(err)
      }
    },
    // 查询某油站可用油品
    async searchGasApi (gasId) {
      try {
        const { code, result = [] } = await searchGas({ gasId: gasId })
        if (code !== 200) return
        this.oilsOptions = result
      } catch (err) {
        console.log(err)
      }
    },
    // 校验接口
    async checkDoorApi () {
      try {
        const { code, result } = await checkDoor()
        if (code !== 200) return
        this.valid = result
      } catch (err) {
        console.log(err)
      }
    },
    // 获取加油站
    async getAllGasStationsApi () {
      try {
        const { code, result = [] } = await getAllGasInfoList()
        if(code !== 200) return
        this.gasOptions = result
      } catch(e) {
        console.log(e)
      }
    },
    // 详情返显接口
    async detailApi (id) {
      try {
        const { code, result } = await checkCoupon({ id: id })
        if(code !== 200) return
        const { gasId, gasName, couponTitle, couponType, couponMoney, couponConditionMoney, expireDateInterval, oils } = result
        const parmas = { couponTitle, couponType, couponMoney, couponConditionMoney, expireDateInterval }
        const res = await searchGas({ gasId: gasId })
        if (res.code !== 200) return
        this.oilsOptions = res.result
        this.oilCouponName = gasName
        parmas.gasId = `${gasId}_${gasName}`
        parmas.couponType = String(couponType)
        oils === '' ? parmas.oils = ['全部油品'] : parmas.oils = oils.split(',')
        this.checkDisabled = true
        this.ruleForm = parmas
      } catch(e) {
        console.log(e)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.container {
  margin-top: 10px;
  background: #fff;
  padding: 0 10px;
  box-shadow: 0px 2px 2px 0px rgba(215, 215, 215, 0.4);
}
.el-form-item .star:before {
  content: '*';
  color: #F56C6C;
  margin-right: 4px;
}
.left {
  padding: 10px;
  >div:nth-child(1) {
    color: #606266
  }
  .title {
    margin: 30px 0;
    font-weight: 600;
  }
  /deep/.el-col {
    padding-left: 0px !important;
  }
  .quan {
    height: 40px;
    display: flex;
    justify-content: center;
    flex-direction: column;
    border: 1px solid #fff;
    >span:nth-child(1) {
      height: 24px;
      font-size: 14px;
      line-height: 24px;
      color: #C0C4CC;
    }
  }
}

.wrap {
  width: 70%;
  height: 200px;
  margin-top: 5px;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0px 2px 7px 0px rgba(0, 0, 0, 0.09);
  .top {
    width: 100%;
    height: 120px;
    display: flex;
    border-bottom: 1px solid #ccc;
    background: linear-gradient(270deg, #8AC2F8 0%, #5293F4 100%);
    .top_left {
      width: 30%;
      height: 100%;
      color: #fff;
      border-right: 1px dotted #ccc;
      display: flex;
      flex-direction: column;
      justify-content: flex-start;
      align-items: center;
      >div:nth-child(1) {
        margin-top: 20px;
        font-size: 30px;
        font-weight: bold;
      }
      >div:nth-child(2) {
        margin-top: 5px;
        font-size: 12px;
      }
    }
    .top_right {
      flex: 1;
      height: 70%;
      display: flex;
      padding-left: 10px;
      flex-direction: column;
      justify-content: center;
      align-items: flex-start;
      div {
        font-size: 12px;
        margin-top: 10px;
        color: #ccc;
      }
      .name {
        font-size: 20px;
        color: #fff;
        font-weight: blod;
      }
    }
  }
  .bo {
    height:3px;
    background: url(../../assets/image/11.png) repeat;
    background-size: 9px 3px;
    margin-top: -3px;
  }
  .middle {
    width: 100%;
    height: 80px;
    color: #606266;
    padding: 10px;
    display: flex;
    align-items: center;
    justify-content: flex-start;
  }
}

.bottom {
  width: 100%;
  height: 100px;

  ul {
    margin: 0;
    padding: 10px;

    li {
      font-size: 14px;
      color: #ccc;
      list-style: none;
    }
  }
}
</style>
